package com.bl.org.service.impl;

import com.bl.org.domain.Department;
import com.bl.org.mapper.DepartmentMapper;
import com.bl.org.service.IDepartmentService;
import com.bl.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Autowired
    private  DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {
        List<Department> allDept = departmentMapper.loadAll();

        Map<Long,Department> map = new HashMap<>();

        for (Department department : allDept) {
            map.put(department.getId(),department);
        }
        //前端需要得到的集合数据 - 部门树
        List<Department> deptTree = new ArrayList<>();
        for (Department department:allDept){
            if(department.getParentId() == null){//顶级部门
                deptTree.add(department);
            }else{//不是顶级部门
                //1.想办法找到当前部门的 父部门
                Long parentId = department.getParentId();
                //下面这种是从Map中去获取的 - 以前装进去的对象还是会存在
                Department parentDepartment = map.get(parentId);
                //2.将自己装到  父部门 的children中
                parentDepartment.getChildren().add(department);
            }
        }
        return deptTree;
    }

    @Override
    public void save(Department department) {
        // 添加操作
        super.save(department);
        // 调用修改方法更新部门路径
        update(department);
    }

    @Override
    public void update(Department department) {
        // 获取自己的id
        if (department.getParentId()==null){  // 没有上级部门
            // 获取自己的id
            Long id = department.getId();
            // 设置自己的id为部门路径
            department.setDirPath("/" + id);
        }else {
            // 获取上级部门id
            Long parentId = department.getParentId();
            // 获取上级部门对象
            Department parentDepartment = departmentMapper.loadById(parentId);
            // 设置上级部门路径
            department.setDirPath(parentDepartment.getDirPath() + "/" + department.getId());
        }
        // 更新对象
        super.update(department);
    }
}
